from .base_strategy import BaseStrategy
import backtrader as bt
# 简单的双均线策略，交叉买入
class MyStrategy(BaseStrategy):
    params = (
     ('short_period', 5),  # 短期均线周期
        ('long_period', 20),  # 长期均线周期
    )
 
    def __init__(self):
        super().__init__()

        self.init_indicators()
        # 用于跟踪订单
        self.order = None
    
    def init_indicators(self):
        """在此定义指标 (EMA/MACD/RSI等)"""
     # 计算短期和长期均线
        self.short_ma = bt.indicators.SMA(self.data.close, period=self.p.short_period)
        self.long_ma = bt.indicators.SMA(self.data.close, period=self.p.long_period)
 
        # 用于跟踪交叉信号
        self.crossover = bt.indicators.CrossOver(self.short_ma, self.long_ma)

    def notify_order(self, order):
        super().notify_order(order)
 
    def next(self):
        super().next()
 
        # 检查是否有持仓
        if not self.position:
            # 如果短期均线上穿长期均线，买入
            if self.crossover > 0:
                self.buy()
        else:
            # 如果短期均线下穿长期均线，卖出
            if self.crossover < 0:
                self.close()